package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.req.IdParam;
import com.example.common.resp.Result;
import com.example.common.utils.VerifyCodeUtils;
import com.example.springboot.dto.LoginResp;
import com.example.springboot.dto.SubmenuResp;
import com.example.springboot.dto.UserResp;
import com.example.springboot.entity.*;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.model.LoginParam;
import com.example.springboot.model.UserSaveParam;
import com.example.springboot.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author he
 * @since 2023-11-14
 */
@Tag(name = "用户")
@RestController
@RequestMapping("/userEntity")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoutingService routingService;
    @Autowired
    private SubmenuService submenuService;
    @Autowired
    private RoutesService routesService;
    @Autowired
    private MenuService menuService;
    private Integer exist;

    /**
     * @param param
     * @return
     */
    @Operation(summary = "是否存在")
    @PostMapping("/exist")
    public Result exist(@RequestBody @Validated IdParam param) {
        QueryWrapper<UserEntity> userEntityQueryWrapper = new QueryWrapper<>();
        userEntityQueryWrapper.eq("id", param.getId());
        exist = 0;
        if (userService.count(userEntityQueryWrapper) == 0) {
            return Result.failure(200, "用户不存在", exist);
        }
        return Result.success("用户存在", 1);
    }

    /**
     * @return
     */
    @Operation(summary = "用户列表")
    @GetMapping("/list")
    public Result<List<UserEntity>> list() {
        ArrayList<UserResp> userRespArrayList = new ArrayList<>();
        List<UserEntity> userEntityList = userService.list();
        for (int i = 0; i < userEntityList.size(); i++) {
            UserEntity userEntity = userEntityList.get(i);
            UserResp userResp = new UserResp();
            BeanUtils.copyProperties(userEntity, userResp);
            userResp.setRoleEntity(roleService.getById(userResp.getRoleId()));
            userRespArrayList.add(userResp);
        }
        return Result.success(userRespArrayList);
    }

    /**
     * @param param
     * @return
     */
    @Operation(summary = "根据id查找")
    @PostMapping("/detail")
    public Result<UserResp> detail(@RequestBody @Validated IdParam param) {
        //ID是否存在
        if (Objects.equals(exist(param).getData().toString(), exist.toString())) {
            return Result.failure(exist(param).getMessage());
        }
        //查找
        UserEntity userEntity = userService.getById(param.getId());
        UserResp userResp = new UserResp();
        BeanUtils.copyProperties(userEntity, userResp);
        userResp.setRoleEntity(roleService.getById(userEntity.getRoleId()));
        return Result.success(userResp);
    }

    /**
     * @param param
     * @return
     */
    @Operation(summary = "保存或修改")
    @PostMapping("/save")
    public Result save(@RequestBody @Validated UserSaveParam param) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(param, userEntity);
        if (userEntity.getId() == 0) {
            userEntity.setId(null);
            userEntity.setCreateTime(new Date());
            userEntity.setUpdateTime(new Date());
            if (userService.save(userEntity)) {
                return Result.success();
            }
            return Result.failure("保存失败，请稍后重试");
        } else {
            userEntity.setUpdateTime(new Date());
            if (userService.updateById(userEntity)) {
                return Result.success();
            }
            return Result.failure("修改失败，请稍后重试");
        }
    }

    /**
     * @param param
     * @return
     */
    @Operation(summary = "根据id删除")
    @PostMapping("/delete")
    public Result delete(@RequestBody @Validated IdParam param) {
        //ID是否存在
        if (Objects.equals(exist(param).getData().toString(), exist.toString())) {
            return Result.failure(exist(param).getMessage());
        }
        //删除
        if (userService.removeById(param.getId())) {
            return Result.success();
        } else {
            return Result.failure("删除失败，请稍后重试");
        }
    }

    /**
     * @param session
     * @param response
     * @throws IOException
     */
    @Operation(summary = "生成验证码")
    @GetMapping("/generateImageCode")
    public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
        //随机生成四位随机数
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //保存到session域中
        session.setAttribute("code", code);
        //根据随机数生成图片，reqponse响应图片
        response.setContentType("image/png");
        ServletOutputStream os = response.getOutputStream();
        VerifyCodeUtils.outputImage(130, 60, os, code);
    }

    /**
     * @param param
     * @param session
     * @return
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginParam param, HttpSession session) {
        //账号是否存在
        QueryWrapper<UserEntity> userEntityQueryWrapper = new QueryWrapper<>();
        userEntityQueryWrapper.eq("userId", param.getUserId());
        if (userMapper.selectCount(userEntityQueryWrapper) == 0) {
            return Result.failure("账号不存在");
        }
        //密码是否正确
        if (!userService.getOne(userEntityQueryWrapper).getPasswd().equals(param.getPasswd())) {
            return Result.failure("密码错误");
        }
        //是否挂失
        if (userService.getOne(userEntityQueryWrapper).getState() == 0) {
            return Result.failure("账号状态异常");
        }
        //验证码是否正确
//        if (!session.getAttribute("code").toString().equals(param.getCode())) {
//            return Result.failure("验证码错误");
//        }
        //基本信息
        LoginResp loginResp = new LoginResp();
        UserEntity one = userService.getOne(userEntityQueryWrapper);
        loginResp.setUserEntityObj(one);
        loginResp.setRoleEntityObj(roleService.getById(one.getRoleId()));
        //权限信息
        QueryWrapper<RoutingEntity> routingEntityQueryWrapper = new QueryWrapper<>();
        routingEntityQueryWrapper.eq("roleId", one.getRoleId());
        List<RoutingEntity> routingEntityList = routingService.list(routingEntityQueryWrapper);
        ArrayList<SubmenuResp> submenuRespArrayList = new ArrayList<>();
        //一级路由信息
        for (RoutingEntity routingEntity : routingEntityList) {
            QueryWrapper<SubmenuEntity> submenuEntityQueryWrapper = new QueryWrapper<>();
            submenuEntityQueryWrapper.eq("id", routingEntity.getSubmenuId());
            submenuEntityQueryWrapper.eq("state", 1);
            SubmenuEntity submenu = submenuService.getOne(submenuEntityQueryWrapper);
            if (submenu != null) {
                SubmenuResp submenuResp = new SubmenuResp();
                BeanUtils.copyProperties(submenu, submenuResp);
                submenuRespArrayList.add(submenuResp);
            }
        }
        loginResp.setSubmenuRespList(submenuRespArrayList);
        //关联路由信息
        for (int i = 0; i < submenuRespArrayList.size(); i++) {
            QueryWrapper<RoutesEntity> routesEntityQueryWrapper = new QueryWrapper<>();
            routesEntityQueryWrapper.eq("submenuId", submenuRespArrayList.get(i).getId());
            List<RoutesEntity> routesEntityList = routesService.list(routesEntityQueryWrapper);
            //二级路由信息
            ArrayList<MenuEntity> menuEntityArrayList = new ArrayList<>();
            for (int j = 0; j < routesEntityList.size(); j++) {
                QueryWrapper<MenuEntity> menuEntityQueryWrapper = new QueryWrapper<>();
                menuEntityQueryWrapper.eq("id", routesEntityList.get(j).getMenuId());
                menuEntityQueryWrapper.eq("state", 1);
                MenuEntity menu = menuService.getOne(menuEntityQueryWrapper);
                if (menu != null) {
                    menuEntityArrayList.add(menu);
                }
            }
            submenuRespArrayList.get(i).setMenuEntityList(menuEntityArrayList);
        }
        //查找关联是否有为0
        List<RoutesEntity> entities = routesService.list();
        for (int i = 0; i < entities.size(); i++) {
            if (entities.get(i).getSubmenuId() == 0) {
                QueryWrapper<MenuEntity> menuEntityQueryWrapper = new QueryWrapper<>();
                menuEntityQueryWrapper.eq("id", entities.get(i).getMenuId());
                menuEntityQueryWrapper.eq("state", 1);
                MenuEntity menuEntity = menuService.getOne(menuEntityQueryWrapper);
                SubmenuResp submenuResp = new SubmenuResp();
                BeanUtils.copyProperties(menuEntity, submenuResp);
                submenuRespArrayList.add(submenuResp);
            }
        }
        //返回结果
        return Result.success(loginResp);
    }
}
